package com.sf.marathon.soul.core.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.sf.marathon.soul.core.base.JsonResult;
import com.sf.marathon.soul.core.base.ResultCodeEnum;


/**
 * 登录操作工具类
 */
public class SignUtils {

    private static Logger logger = LoggerFactory.getLogger(SignUtils.class);

    public static final Map<String, Long> xTokens = new ConcurrentHashMap<>(10);

    private SignUtils() {
    }

    /**
     * 以JSON格式输出跳转地址
     *
     * @param response
     * @param redirectUrl
     * @param type        TIMEOUT-未登陆或登陆超时 LOGIN-登陆成功
     */
    public static void responseRedirectJson(HttpServletResponse response, String redirectUrl, ResultCodeEnum type) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            String outStr = JSON.toJSONString(getRedirectResult(redirectUrl, type));
            out = response.getWriter();
            out.append(outStr);
            response.flushBuffer();
        } catch (IOException e) {
            logger.error("error:", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    public static void responseRedirectJson(HttpServletResponse response, String redirectUrl) {
        responseRedirectJson(response, redirectUrl, ResultCodeEnum.TIMEOUT);
    }


    /**
     * 根据类型返回跳转json
     *
     * @param redirectUrl
     * @param type        TIMEOUT-未登陆或登陆超时 LOGIN-登陆成功
     * @return
     */
    private static JsonResult getRedirectResult(String redirectUrl, ResultCodeEnum type) {
        JsonResult result = new JsonResult(type);
        result.setData(redirectUrl);
        return result;
    }

    /**
     * 返回无权限访问该资源
     *
     * @return
     */
    private static JsonResult getUnauthorized(String reqURI) {
        JsonResult result = new JsonResult(ResultCodeEnum.UNAUTHORIZED);
        result.setMessage("当前登录用户无权限访问资源:" + reqURI);
        return result;
    }
}
